package com.best4cloud.user.service.impl;

import com.best4cloud.common.core.exception.BusinessException;
import com.best4cloud.user.domain.SysUser;
import com.best4cloud.user.domain.repository.SysUserRepository;
import com.best4cloud.user.service.SysUserService;
import com.best4cloud.user.web.rest.request.SysLoginQuery;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class SysUserServiceImpl implements SysUserService {

    private final SysUserRepository sysUserRepository;

    private final PasswordEncoder passwordEncoder;

    @Override
    public SysUser login(SysLoginQuery loginDTO) {
        // 查询用户
        SysUser sysUser = sysUserRepository.findOne(loginDTO.createSpec()).orElseThrow(() -> new UsernameNotFoundException("用户名不存在"));

        if (!passwordEncoder.matches(loginDTO.getPassword(), sysUser.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }
        return sysUser;
    }

    @Override
    public SysUser findById(Long id) {
        return sysUserRepository.findById(id).orElseThrow(() -> new BusinessException("无法获取该用户信息！"));
    }

    @Override
    public SysUser getUserByUsername(String username) {
        return sysUserRepository.findByUsername(username);
    }
}
